package com.dong.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.dong.test.T060ProfileTest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Profile:
 *      spring 为我们可以根据当前环境,动态的激活和切换一系列bean的功能
 *
 *      项目不同环境 开发环境,测试环境,生产环境
 *       没有标注profile就是  default  ,全部激活
 *
 *
 *      方法1  命令行参数   -Dspring.profiles.active=test
 *      方法2  使用代码方式
 *      @see T060ProfileTest
 */
@PropertySource("classpath:db.properties")
@Configuration
public class T060ProfileConfig implements EmbeddedValueResolverAware {
    @Value("${db.user}")
    private String user;
   // @Value("${db.driverClass}")
    private String driverClass;
    @Bean
    @Profile("test")
    public DataSource dataSourceTest(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
      dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    @Bean
    @Profile("dev")
    public DataSource dataSourceDev(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    @Bean
    @Profile("prd")
    public DataSource dataSourcePrd(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/prd");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.driverClass = resolver.resolveStringValue("${db.driverClass}");
    }
}
